# 贷款api
# 加载系统库
from django.db.models import F
from django.http import JsonResponse
from django import forms
from django.forms.models import model_to_dict

# 加载数据库
from web.models import Users,  LoanOrder, RealNameIdentity

# 加载自定义工具库
from web import Tools



class FormsModel(forms.ModelForm):
    class Meta:
        model = LoanOrder
        fields = "__all__"

def filter_model_to_dict(data, template=0, filter=0):
    """
    过滤model_to_dict
    :param data:
    :param template:
    :return:
    """
    data.repayment_time = data.repayment_time.strftime("%Y-%m-%d")
    new_data = model_to_dict(data)
    # 删除id
    del new_data["id"]

    if template == 0:
        user_name = RealNameIdentity.objects.filter(user=data.user.id).first()
        new_data["user_info"] = {
            "user_number": data.user.user_number,
            "name": user_name.name,
            "phone": data.user.phone,
            "user_avatar_img": data.user.user_avatar_img.url,
            "user_is_authenticated": data.user.user_is_authenticated,
            "loan_default_amount": data.user.loan_default_amount,
        }
        new_data["loan_method"] = data.get_loan_method_display()

        new_data["create_time"] = data.create_time.strftime("%Y-%m-%d")

        # 判断 loan_time 与 repayment_time 的时间差，单位是天
        if data.loan_time:
            new_data["loan_time"] = data.loan_time.strftime("%Y-%m-%d")




    elif template == 1:
        pass
    else:
        pass

    if filter == 1:
        new_data["status"] = data.get_status_display()
    return new_data


# 用户额度减免
def jdmq(order):
    try:
        # 判断用户额度是否足够
        if Users.objects.filter(id=order.instance.user.id).first().loan_default_amount < order.instance.amount:
            return False

        # 减少用户额度
        Users.objects.filter(id=order.instance.user.id).update(loan_default_amount=Users.objects.filter(
            id=order.instance.user.id).first().loan_default_amount - order.instance.amount)
        return True

    except Exception as e:
        return False



# 创建订单
def create_order(request):
    if request.method == 'POST':
        order = FormsModel(request.POST)
        if order.is_valid():
          user_info = Users.objects.filter(id=order.instance.user.id).first()
          # 判断用户是否实名
          if not RealNameIdentity.objects.filter(user=user_info.id).first().is_audit:
              if user_info.user_is_authenticated == 0:
                  return JsonResponse(Tools.ReturnData(code=401, msg="请前往实名认证"))
              elif user_info.user_is_authenticated == 2:
                  return JsonResponse(Tools.ReturnData(code=402, msg="实名认证被拒绝"))



          if not jdmq(order):
                return JsonResponse(Tools.ReturnData(code=400, msg="额度不足", data={
                    "amount": user_info.loan_default_amount,
                    "order_amount": order.instance.amount
                }))
          else:
                # 最少要借1元
                if order.instance.amount < 1:
                  return JsonResponse(Tools.ReturnData(code=400, msg="最少要借1元"))


                order.save()
                return JsonResponse(Tools.ReturnData(msg="申请通过，待审核", data=filter_model_to_dict(order.instance)))
        else:
            error_info = Tools.Forms_GetError(order)
            return JsonResponse(Tools.ReturnData(code=400, msg=error_info[1], data=error_info[0]))
    return JsonResponse(Tools.ReturnData(msg="请使用POST请求", template=1))


# 获取我的订单
def my_order(request):
    if request.method == 'GET':
        user_id = request.GET.get("user_id")
        if user_id:
            data = LoanOrder.objects.filter(user=user_id).order_by("-id")
            if data:
                data = [filter_model_to_dict(i) for i in data]
                return JsonResponse(Tools.ReturnData(msg="获取成功", data=data))
            return JsonResponse(Tools.ReturnData(code=400, msg="未找到订单"))
        return JsonResponse(Tools.ReturnData(code=400, msg="未登录"))
    return JsonResponse(Tools.ReturnData(msg="请使用GET请求", template=1))


# 根据条件获取订单
def get_order(request):
    if request.method == 'GET':
        user_id = request.GET.get("user_id")
        status = request.GET.get("status")
        if user_id:
            if status:
                data = LoanOrder.objects.filter(user=user_id, status=status)
            else:
                data = LoanOrder.objects.filter(user=user_id)
            if data:
                data = [filter_model_to_dict(i) for i in data]
                return JsonResponse(Tools.ReturnData(msg="获取成功", data=data))
            return JsonResponse(Tools.ReturnData(code=400, msg="未找到订单"))
        return JsonResponse(Tools.ReturnData(code=400, msg="未登录"))
    return JsonResponse(Tools.ReturnData(msg="请使用GET请求", template=1))


# 放款
from datetime import datetime

def loan(request):
    if request.method != 'POST':
        return JsonResponse(Tools.ReturnData(template=1))

    # 放款金额
    loan_amount = request.POST.get("loan_amount")
    # 放款方式
    loan_method = request.POST.get("loan_method")
    # 订单编号
    loan_order_number = request.POST.get("loan_order_number")

    if not (loan_amount and loan_method  and loan_order_number):
        return JsonResponse(Tools.ReturnData(code=400, msg="请提供订单编号"))

    # 获取订单
    data = LoanOrder.objects.filter(loan_order_number=loan_order_number).first()
    if not data:
        return JsonResponse(Tools.ReturnData(code=400, msg="订单不存在"))

    # 判断订单状态
    if data.status != 0:
        return JsonResponse(Tools.ReturnData(code=400, msg="订单状态不正确"))

    # 判断放款金额是否正确
    try:
        loan_amount = int(loan_amount)
        loan_method = int(loan_method)
    except ValueError:
        return JsonResponse(Tools.ReturnData(code=400, msg="放款金额或放款方式格式不正确"))

    if data.amount != loan_amount:
        return JsonResponse(Tools.ReturnData(code=400, msg="放款金额不正确"))

    # 判断放款方式是否正确
    if data.loan_method != loan_method:
        return JsonResponse(Tools.ReturnData(code=400, msg="放款方式不正确"))


    # 更新订单信息
    data.loan_amount = loan_amount
    data.status = 3
    # 更新放款时间
    data.loan_time = datetime.now()
    data.save()

    return JsonResponse(Tools.ReturnData(msg="放款成功"))


def loan_reject(request):
    if request.method != 'POST':
        return JsonResponse(Tools.ReturnData(template=1))
    loan_order_number = request.POST.get("loan_order_number")
    if not loan_order_number:
        return JsonResponse(Tools.ReturnData(code=400, msg="请提供订单编号"))
    data = LoanOrder.objects.filter(loan_order_number=loan_order_number).first()
    if not data:
        return JsonResponse(Tools.ReturnData(code=400, msg="订单不存在"))
    if data.status != 0:
        return JsonResponse(Tools.ReturnData(code=400, msg="订单状态不正确"))
    data.status = 2
    data.update_time = datetime.now()
    Users.objects.filter(id=data.user.id).update(loan_default_amount=F("loan_default_amount") + data.amount)
    data.save()
    return JsonResponse(Tools.ReturnData(msg="已拒绝"))


def loan_list(request):
    if request.method == "POST":
        status = request.POST.get("status")
        loan_order_number = request.POST.get("loan_order_number")

        if status:
            loan_lists = [filter_model_to_dict(i, filter=1) for i in LoanOrder.objects.filter(status=status, loan_order_number__contains=loan_order_number)]
        else:
            loan_lists = [filter_model_to_dict(i, filter=1) for i in LoanOrder.objects.filter(status__in=[3, 5])]
        return JsonResponse(Tools.ReturnData(data=loan_lists))
    return JsonResponse(Tools.ReturnData(template=1))

